const {access, readdir, mkdirSync, writeFile, constants, stat} = require('fs');
const path = require('path');
const {promisify} = require('util');

const accessify = promisify(access),
  readdirify = promisify(readdir),
  statify = promisify(stat),
  writeFileify = promisify(writeFile);
const arr = [];
const directories = ['src/pages', 'src/components']

async function checkDir() {
  try {
    await accessify('./output', constants.F_OK);
  } catch (error) {
    mkdirSync(path.join(__dirname, 'output'));
  }
}

function slash(str) {
	var isExtendedLengthPath = /^\\\\\?\\/.test(str);
	var hasNonAscii = /[^\x00-\x80]+/.test(str);

	if (isExtendedLengthPath || hasNonAscii) {
		return str;
	}

	return str.replace(/\\/g, '/');
}

async function walk(dir) {
  try {
    let files = await readdirify(dir);
    files = await Promise.all(files.map(async file => {
      const filePath = path.join(dir, file);
      const stats = await statify(filePath);
      if (stats.isDirectory()) {
        return walk(filePath);
      } else if (stats.isFile()) {
        const myPath = slash('../..' + filePath.split('src')[1])
        return myPath
      }
    }))
    files = files.filter(item => checkType(item));
    return files.reduce((all, folderContents) => all.concat(folderContents), []);
  } catch (error) {
    console.log(`Err: ${error}`);
  }
}

function checkType(filePath) {
  const re = /\.(png|jpg|jpeg)$/ig;
  return re.test(filePath);
}

async function main() {
  try {
    await checkDir();
    const dirs = await Promise.all(directories.map(async dir => {
      const retrievePath = path.join(__dirname, dir);
      const val = await walk(retrievePath);
      return val;
    }));
    const concatDirs = dirs.reduce((acc, cur) => acc.concat(cur), []);
    concatDirs.map(item => {
      arr.push({src: `require('${item}')`})
    })
    await writeFileify(path.join(__dirname, '/output/a.js'), JSON.stringify(arr).replace(/:"/gm, ':').replace(/\)"/gm, ')'));
    console.log('completed');
  } catch (error) {
    console.log(`Error: ${error}`);
  }
}
main();
